//
//  DBConnection.m
//  client1
//
//  Created by koolearn on 11-3-31.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DBConnection.h"
#import "Statement.h"

static sqlite3* theDatabase = nil;


@interface DBConnection (private)
+ (void) createDatabase:(NSString *)dbPath;
+ (NSString*) getDBPath;
@end


@implementation DBConnection

+ (void) createEditableCopyOfDatabaseIfNeeded: (BOOL) forceCreate 
{
	NSString* dbPath = [DBConnection getDBPath];
	
	NSError* error;
	NSFileManager* fileManager = [NSFileManager defaultManager];
	
	if ( forceCreate ) {
		[fileManager removeItemAtPath:dbPath error:&error];
	}
	
	if ( ![fileManager fileExistsAtPath:dbPath] ) {
		//create database
		[DBConnection createDatabase : dbPath];
	}
}


+ (void) createDatabase : (NSString*) dbPath
{
	NSString* defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DATABASE_NAME];
	NSError* error;
	BOOL success = [[NSFileManager defaultManager] copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
	NSAssert1( success, @"Fail to create database, error: %@", [error localizedDescription] );
}


+ (NSString*) getDBPath 
{
	NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString* documentPath = [paths objectAtIndex:0];
	NSString* dbPath = [documentPath stringByAppendingPathComponent:DATABASE_NAME];
	return dbPath;
}


+ (sqlite3*) getDatabase
{
	if ( theDatabase != nil ) return theDatabase;
	
	NSString* dbPath = [DBConnection getDBPath];
	int result = sqlite3_open( [dbPath UTF8String], &theDatabase );
	if ( result != SQLITE_OK ) {
		sqlite3_close( theDatabase );
		[DBConnection createEditableCopyOfDatabaseIfNeeded:YES];
		NSAssert( 0, @"open database fail" );
	}
	
	return theDatabase;
}


+ (void) close
{
	if ( theDatabase != nil ) {
		sqlite3_close( theDatabase );
	}
}


+ (void)beginTransaction
{
    char *errmsg;     
    sqlite3_exec(theDatabase, "BEGIN", NULL, NULL, &errmsg);     
}


+ (void)commitTransaction
{
    char *errmsg;     
    sqlite3_exec(theDatabase, "COMMIT", NULL, NULL, &errmsg);     
}


+ (long long) createRandomNum:(NSInteger)bit
{
    NSMutableString* s = [[NSMutableString alloc] init];
    for ( int i=0; i<bit; i++ ) {
        int randNum = arc4random() % 10;
        [s appendString:[NSString stringWithFormat:@"%d", randNum]];
    }
    
    return [s longLongValue];
}


+ (void) execute:(char*)sql
{
	sqlite3* db = [DBConnection getDatabase];
	Statement* stmt = [[Statement alloc] initWithDB:db sql:sql];
	
	if ( [stmt step] != SQLITE_DONE ) {
		[stmt release];
		NSAssert2( 0, @"Fail to prepare statement: %s (%s)", sql, sqlite3_errmsg(db) );
		return;
	}
	
	[stmt release];
}


@end
